package com.cbg.config;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateProperties;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateSettings;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.util.Map;

/**
 * 标签数据源配置
 *
 * @author wangjuzheng
 * @date 2019-11-20
 **/

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef = "symEsSearchManageEntityManagerFactory"
        , transactionManagerRef = "symEsSearchManageTransactionManager"
        , basePackages = {"com.shuyuwl.core.repository", "com.shuyuwl.repository", "com.cbg.es.repository", "com.cbg.archives.repository"})
public class SymConfig {

    @Resource
    @Qualifier("symDataSource")
    private DataSource dataSource;

    @Autowired
    private HibernateProperties hibernateProperties;

    @Autowired
    JpaProperties jpaProperties;

    @Primary
    @Bean(name = "symEsSearchManageEntityManagerFactory")
    public LocalContainerEntityManagerFactoryBean symEntityManagerFactory(EntityManagerFactoryBuilder builder) {

        Map<String, Object> properties = hibernateProperties.determineHibernateProperties(
                jpaProperties.getProperties(), new HibernateSettings());
        LocalContainerEntityManagerFactoryBean em = builder.dataSource(dataSource)
                .properties(properties)
                .packages("com.shuyuwl.*.entity",
                        "com.shuyuwl.entity",
                        "com.shuyuwl.domain",
                        "com.shuyuwl.*.domain",
                        "com.cbg.*.entity",
                        "com.cbg.entity",
                        "com.cbg.domain",
                        "com.cbg.*.domain")
                .persistenceUnit("jpaPersistenceUnit")
                .build();
        return em;
    }

    @Primary
    @Bean(name = "symEsSearchManageTransactionManager")
    PlatformTransactionManager symTransactionManager(EntityManagerFactoryBuilder builder) {
        return new JpaTransactionManager(symEntityManagerFactory(builder).getObject());
    }
}